﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NReader.Model.RAS;
using NReader.Service;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Common;

// “分组项页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234231 上提供

namespace XnReader.WinRT
{
    /// <summary>
    /// 显示分组的项集合的页。
    /// </summary>
    public sealed partial class Index
    {
        private IList<SysWebInfo> _sysWebInfos;

        private List<GroupInfoList<object>> _groupInfoList;

        public Index()
        {
            InitializeComponent();

            var toolBar = new ToolBarInfo
                              {
                                  VisibleRights = Visibility.Visible,
                                  VisibleSearch = Visibility.Visible,
                                  VisibleProtocol = Visibility.Visible,
                                  VisibleRefresh = Visibility.Visible
                              };
            if (tlBottom != null)
            {
                tlBottom.DataContext = toolBar;
                tlBottom.RefreshClickEvent += TlBottomRefreshClickEvent;
            }
        }

        private void TlBottomRefreshClickEvent(object sender, RoutedEventArgs e)
        {
            Frame.Navigate(typeof(Index));
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected override async void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            try
            {
                //从挂起恢复的操作或网络链接失败
                if ((pageState != null
                         && pageState.ContainsKey("Page")
                         && pageState["Page"].ToString().Equals("Index"))
                     || await Helper.GlobalUtils.CheckConnectionState() == false)
                {
                    //_groupInfoList = await GlobalService.Instance().GetIndexGroupListFromLocal();
                    //cvs2.Source = _groupInfoList;
                    pbLoading.IsActive = false;
                    _sysWebInfos = await GlobalService.Instance().GetSysWebInfosFromLocal();
                }
                else //从导航的操作
                {
                    //_groupInfoList = await GlobalService.Instance().GetIndexGroupList();
                    //cvs2.Source = _groupInfoList;
                    pbLoading.IsActive = false;
                    _sysWebInfos = await GlobalService.Instance().GetSysWebList();
                    await Task.Run(() => SaveIndex());
                }
            }
            catch (Exception ex)
            {
                var md = new MessageDialog("书籍列表加载错误.请检查您的网络链接是否正确");
                md.ShowAsync();
                //throw;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ItemsByLetterItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem != null)
            {
                int articleid = ((ArticleInfo) e.ClickedItem).articleid;
                Frame.Navigate(typeof (Book), articleid);
            }
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
            pageState["Page"] = "Index";
            base.SaveState(pageState);
        }

        private async Task SaveIndex()
        {
            if (_sysWebInfos != null)
            {
                await GlobalService.Instance().SaveSysWebInfos(_sysWebInfos);
            }
            //if (_groupInfoList != null)
            //{
            //    await GlobalService.Instance().SaveIndexGroupList(_groupInfoList);
            //}
        }
    }
}
